/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.icanci.loopstack.damc.api.groovy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;

import cn.icanci.loopstack.damc.spi.model.refresh.RefreshCell;

public final class GroovyScriptRepository {
    public static final Map<MethodMockCacheKey, String> SCRIPT_REPOSITORY = new HashMap<>();

    public static void refreshCache(List<RefreshCell> classes) {
        for (RefreshCell cell : classes) {
            String clazzName = cell.getClazz();
            List<RefreshCell.Cell> cells = cell.getCells();
            if (CollectionUtils.isEmpty(cells)) {
                // 清空所有的缓存数据
                doRemoveCache(clazzName);
            } else {
                doRefreshCache(cells, clazzName);
            }
        }
    }

    private static void doRefreshCache(List<RefreshCell.Cell> cells, String clazzName) {
        for (RefreshCell.Cell innerCell : cells) {
            MethodMockCacheKey cacheKey = new MethodMockCacheKey(clazzName, innerCell.getMethodName(), innerCell.getDescriptor());
            SCRIPT_REPOSITORY.put(cacheKey, innerCell.getScript());
            GroovyScriptClassRepository.add(cacheKey, innerCell.getScript());
        }
    }

    private static void doRemoveCache(String clazzName) {
        Set<MethodMockCacheKey> cacheKeys = SCRIPT_REPOSITORY.keySet();
        Set<MethodMockCacheKey> removeCacheKeys = cacheKeys.stream().filter(key -> StringUtils.equals(key.getClazzName(), clazzName)).collect(Collectors.toSet());
        for (MethodMockCacheKey removeCacheKey : removeCacheKeys) {
            SCRIPT_REPOSITORY.remove(removeCacheKey);
            GroovyScriptClassRepository.remove(removeCacheKey);
        }
    }

    public static String getScript(String clazzName, String methodName, String descriptor) {
        MethodMockCacheKey cacheKey = new MethodMockCacheKey(clazzName, methodName, descriptor);
        return SCRIPT_REPOSITORY.get(cacheKey);
    }

    public static List<RefreshCell> getRefreshCells() {
        List<MethodMockCache> caches = Lists.newArrayList();
        for (Map.Entry<MethodMockCacheKey, String> entry : SCRIPT_REPOSITORY.entrySet()) {
            MethodMockCacheKey key = entry.getKey();
            String value = entry.getValue();
            MethodMockCache methodMockCache = new MethodMockCache(key.getClazzName(), key.getMethodName(), key.getDescriptor(), value);
            caches.add(methodMockCache);
        }
        if (CollectionUtils.isEmpty(caches)) {
            return Lists.newArrayList();
        }
        Map<String, List<MethodMockCache>> group = caches.stream().collect(Collectors.groupingBy(MethodMockCache::getClazzName));

        List<RefreshCell> cells = Lists.newArrayList();
        for (Map.Entry<String, List<MethodMockCache>> entry : group.entrySet()) {
            String clazzName = entry.getKey();
            List<RefreshCell.Cell> innerCells = Lists.newArrayList();
            for (MethodMockCache cache : entry.getValue()) {
                RefreshCell.Cell innerCell = new RefreshCell.Cell();
                innerCell.setMethodName(cache.getMethodName());
                innerCell.setDescriptor(cache.getDescriptor());
                innerCell.setScript(cache.getScript());
                innerCells.add(innerCell);
            }

            RefreshCell cell = new RefreshCell();
            cell.setClazz(clazzName);
            cell.setCells(innerCells);
            cells.add(cell);
        }
        return cells;
    }
}